package io.minio.spring.boot.autoconfigure;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author CSY
 * @date 2025 - 09 - 15
 */
public class MinioOptions {
    private MinioClient minioClient;
    private String bucketName;

    public MinioOptions(MinioClient minioClient, String bucketName) {
        this.minioClient = minioClient;
        this.bucketName = bucketName;
        initialize();
    }

    public void upload(String path, String contentType, long size, InputStream inputStream){
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(path)
                    .contentType(contentType)
                    .stream(inputStream,size,-1).build());
        } catch (Exception e) {
            throw new RuntimeException("上传失败："+e);
        }
    }

    /**
     * 创建桶
     */
    public void initialize() {
        try {
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            throw new RuntimeException("桶创建失败："+e);
        }
    }
}
